/**
 * 凭证 - 新建或编辑界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.Voucher.EditForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    selectedOrg: "",
    selectedWord: "",
    currentVoucherDT: "",
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    // 这个变量用于控制第一次设置凭证（从界面PSI.SLN0002.Voucher.SelectOrgAndWordForm中选择的凭证字）
    me._initedWord = false;

    me._readonly = false;
    const entity = me.getEntity();
    me.adding = entity == null;

    const action = entity == null ? "新建" : "编辑";
    const title = me.formatTitleLabel("记账凭证", action);

    // 组织机构
    const modelName = me.buildModelName(me, "Org");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    // 凭证字
    const modelNameWord = me.buildModelName(me, "VoucherWord");
    PCL.define(modelNameWord, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    PCL.apply(me, {
      header: false,
      padding: "0 0 0 0",
      border: 0,
      maximized: true,
      layout: "border",
      tbar: [{
        id: me.buildId(me, "dfTitle"),
        value: title, xtype: "displayfield"
      }, "->", {
        text: "保存 <span class='PSI-shortcut-DS'>Alt + S</span>",
        tooltip: me.buildTooltip("快捷键：Alt + S"),
        ...PSI.Const.BTN_STYLE,
        iconCls: "PSI-button-ok",
        handler: me._onOK,
        scope: me,
        id: me.buildId(me, "buttonSave")
      }, "-", {
        text: "取消",
        iconCls: "PSI-tb-close",
        ...PSI.Const.BTN_STYLE,
        handler() {
          if (me._readonly) {
            me.close();
            return;
          }

          me.confirm("请确认是否取消当前操作？", () => {
            me.close();
          });
        },
        scope: me,
        id: me.buildId(me, "buttonCancel")
      }, "-", {
        margin: "5 5 5 0",
        cls: "PSI-toolbox",
        labelWidth: 0,
        width: 90,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield"
      }],
      items: [{
        region: "center",
        border: 0,
        bodyPadding: 10,
        layout: "border",
        items: [{
          region: "center",
          layout: "fit",
          border: 1,
          items: me.getVoucherDetailGrid()
        }, {
          region: "south",
          height: 300,
          split: true,
          header: {
            title: `<span style='border-left:4px #2c9ba0 solid;font-size:14px;padding-left:4px;'>分录附加项</span>
                    <span style='color:#d9d9d9; font-size:12px;'> 提示: 回车键跳转输入项</span>`,
            height: 32,
          },
          border: 1,
          layout: "fit",
          items: [
            {
              id: me.buildId(me, "panelFmtCols"),
              border: 0,
              xtype: "panel",
              layout: {
                type: "table",
                columns: 4,
                tableAttrs: PSI.Const.TABLE_LAYOUT,
              },
              bodyPadding: 5,
              items: []
            }
          ]
        }]
      }, {
        region: "north",
        border: 0,
        layout: {
          type: "table",
          columns: 4,
          tableAttrs: PSI.Const.TABLE_LAYOUT_SMALL,
        },
        height: 105,
        bodyPadding: 10,
        items: [{
          xtype: "hidden",
          id: me.buildId(me, "hiddenId"),
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          id: me.buildId(me, "editOrg"),
          labelWidth: 70,
          width: 440,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "组织机构",
          xtype: "combobox",
          queryMode: "local",
          editable: false,
          valueField: "id",
          displayField: "name",
          store: PCL.create("PCL.data.Store", {
            model: modelName,
            autoLoad: false,
            data: []
          }),
          colspan: 4,
          listeners: {
            beforeselect: {
              fn() {
                if (me.getVoucherDetailGrid().getStore().getCount() > 1) {
                  me.showInfo("已经录入凭证分录，不能再更改组织机构");
                  return false;
                }

                return true;
              },
              scope: me,
            },
            select: {
              fn() {
                me.queryVoucherWord();
              },
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editWord"),
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "凭证字",
          xtype: "combobox",
          queryMode: "local",
          editable: false,
          valueField: "id",
          displayField: "name",
          store: PCL.create("PCL.data.Store", {
            model: modelNameWord,
            autoLoad: false,
            data: []
          }),
        }, {
          id: me.buildId(me, "editRef"),
          fieldLabel: "凭证号",
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          xtype: "displayfield",
          value: me.toFieldNoteText("保存后自动生成"),
        }, {
          id: me.buildId(me, "editVoucherDT"),
          fieldLabel: "凭证日期",
          labelWidth: 95,
          labelAlign: "right",
          labelSeparator: "",
          allowBlank: false,
          blankText: "没有输入凭证日期",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "datefield",
          format: "Y-m-d",
          value: new Date(me.getCurrentVoucherDT()),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
          colspan: 2,
        }, {
          id: me.buildId(me, "editChargeUser"),
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "会计主管",
          xtype: "psi_userfield",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editCashUser"),
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "出纳",
          xtype: "psi_userfield",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editBizUser"),
          labelWidth: 95,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "业务责任人",
          xtype: "psi_userfield",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          fieldLabel: "原始凭证数",
          labelAlign: "right",
          labelSeparator: "",
          labelWidth: 95,
          width: 220,
          xtype: "fieldcontainer",
          layout: "hbox",
          items: [{
            id: me.buildId(me, "editBillNumber"),
            xtype: "numberfield",
            allowDecimals: false,
            minValue: 0,
            value: 0,
            hideTrigger: true,
            beforeLabelTextTpl: PSI.Const.REQUIRED,
            width: 40,
            listeners: {
              specialkey: {
                fn: me._onEditBillNumberSpecialKey,
                scope: me
              }
            }
          }, {
            xtype: "displayfield", value: "张", width: 15,
          }],
        }]
      }],
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      }
    });

    me.callParent(arguments);

    me.dfTitle = PCL.getCmp(me.buildId(me, "dfTitle"));

    me.buttonSave = PCL.getCmp(me.buildId(me, "buttonSave"));
    me.buttonCancel = PCL.getCmp(me.buildId(me, "buttonCancel"));

    me.hiddenId = PCL.getCmp(me.buildId(me, "hiddenId"));
    me.editRef = PCL.getCmp(me.buildId(me, "editRef"));
    me.editOrg = PCL.getCmp(me.buildId(me, "editOrg"));
    me.editWord = PCL.getCmp(me.buildId(me, "editWord"));
    me.editVoucherDT = PCL.getCmp(me.buildId(me, "editVoucherDT"));
    me.editChargeUser = PCL.getCmp(me.buildId(me, "editChargeUser"));
    me.editBizUser = PCL.getCmp(me.buildId(me, "editBizUser"));
    me.editCashUser = PCL.getCmp(me.buildId(me, "editCashUser"));
    me.editBillNumber = PCL.getCmp(me.buildId(me, "editBillNumber"));

    me.panelFmtCols = PCL.getCmp(me.buildId(me, "panelFmtCols"));

    // AFX
    me.__editorList = [
      me.editVoucherDT, me.editChargeUser, me.editCashUser, me.editBizUser, me.editBillNumber,
    ];

    me.editOrg.setReadOnly(true);

    me._keyMap = PCL.create("PCL.util.KeyMap", PCL.getBody(), {
      key: "S",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        if (me._readonly) {
          return;
        }

        me._onOK.apply(me, []);
      },
      scope: me
    });

    if (me.adding) {
      me.queryCompanyList();
    }
  },

  /**
   * @private
   */
  _onEditBillNumberSpecialKey(field, e) {
    const me = this;

    if (me._readonly) {
      return;
    }

    if (e.getKey() == e.ENTER) {
      const store = me.getVoucherDetailGrid().getStore();
      if (store.getCount() == 0) {
        store.add({});
      }
      me.getVoucherDetailGrid().focus();
      me._cellEditing.startEdit(0, 1);
    }
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    me._keyMap.destroy();

    PCL.WindowManager.hideAll();

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    me.getVoucherDetailGrid().getStore().add({});

    me.setFocusAndCursorPosToLast(me.editVoucherDT)

    // 下面是编辑凭证
    if (!me.adding) {
      const el = me.getEl() || PCL.getBody();
      el.mask(PSI.Const.LOADING);
      me.ajax({
        url: me.URL("SLN0002/Voucher/voucherInfo"),
        params: {
          id: me.getEntity().get("id"),
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);

            me.editOrg.setReadOnly(true);
            me.editOrg.getStore().add(data.company);
            me.editOrg.setValue(data.company[0].id);
            me.editWord.setReadOnly(true);
            me.editWord.setValue(data.word);
            me.editRef.setValue(me.toFieldNoteText(data.ref));
            me.editVoucherDT.setValue(data.voucherDT);

            me.editChargeUser.setIdValue(data.chargeUserId);
            me.editChargeUser.setValue(data.chargeUserName);
            me.editCashUser.setIdValue(data.cashUserId);
            me.editCashUser.setValue(data.cashUserName);
            me.editBizUser.setIdValue(data.bizUserId);
            me.editBizUser.setValue(data.bizUserName);

            me.editBillNumber.setValue(data.billNumber);

            const store = me.getVoucherDetailGrid().getStore();
            store.removeAll();
            store.add(data.items);

            if (data.voucherStatus && data.voucherStatus != 0) {
              me.setVoucherReadonly();
            } else {
              me.setFocusAndCursorPosToLast(me.editVoucherDT);
            }
          }
        }
      });

    }
  },

  /**
   * @private
   */
  queryCompanyList() {
    const me = this;
    const store = me.editOrg.getStore();
    const r = {
      url: me.URL("SLN0002/Voucher/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            me.editOrg.setValue(me.getSelectedOrg());
          }

          me.queryVoucherWord();
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  queryVoucherWord() {
    const me = this;
    const store = me.editWord.getStore();
    const r = {
      url: me.URL("SLN0002/Voucher/queryVoucherWord"),
      params: {
        orgId: me.editOrg.getValue(),
      },
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (data.length > 0) {
            if (!me._initedWord) {
              me.editWord.setValue(me.getSelectedWord());
              me._initedWord = true;
            } else {
              me.editWord.setValue(data[0]["id"]);
            }
          }
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onOK() {
    const me = this;

    // 检查分录金额合计是否相等
    const store = me.getVoucherDetailGrid().getStore();
    let dbSum = 0;
    let crSum = 0;
    let found = false;
    for (let i = 0; i < store.getCount(); i++) {
      const item = store.getAt(i);

      const subjectCode = item.get("subjectCode");
      if (subjectCode) {
        found = true;
      }

      let debit = parseFloat(item.get("debit"));
      if (isNaN(debit)) {
        debit = 0;
      }
      let credit = parseFloat(item.get("credit"));
      if (isNaN(credit)) {
        credit = 0;
      }

      dbSum += debit;
      crSum += credit;
    }

    if (!found) {
      me.showInfo("没有录入分录科目信息，无法保存", () => {
        me._cellEditing.startEdit(0, 1);
      });
      return;
    }

    if (dbSum != crSum) {
      me.confirm("借贷金额合计不平，请确认是否仍然要保存本凭证？", () => {
        me.doOK(true);
      });
    } else {
      me.doOK(false);
    }
  },

  /**
   * @private
   */
  doOK(ignoreBalance) {
    const me = this;

    PCL.getBody().mask("正在保存中...");
    me.ajax({
      url: me.URL("SLN0002/Voucher/editVoucher"),
      params: {
        adding: me.adding ? "1" : "0",
        jsonStr: me.getSaveData(ignoreBalance)
      },
      callback(options, success, response) {
        PCL.getBody().unmask();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          if (data.success) {
            me.close();
            const pf = me.getParentForm();
            if (pf) {
              pf.refreshMainGrid.apply(pf, [data.id]);
            }
            me.tip("成功保存数据", true);
          } else {
            me.showInfo(data.msg, () => {
              me.editVoucherDT.focus();
            });
          }
        }
      }
    });
  },

  /**
   * @private
   */
  getVoucherDetailGrid() {
    const me = this;
    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "VoucherDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "subjectCode", "subjectName", "debit", "credit",
        "summary", "fmtCols",
      ]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._cellEditing = PCL.create("PSI.UX.CellEditing", {
      clicksToEdit: 1,
      listeners: {
        edit: {
          fn: me._onCellEditingAfterEdit,
          scope: me
        },
        validateedit: {
          fn(editor, e) {
            // 借方金额和贷方金额，这两者只能输入一个
            if (e.field == "debit") {
              const d = e.value;
              if (d !== null) {
                e.record.data["credit"] = null;
                e.record.commit();
              }
            }
            if (e.field == "credit") {
              const d = e.value;
              if (d !== null) {
                e.record.data["debit"] = null;
                e.record.commit();
              }
            }
          },
          scope: me,
        }
      }
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-EF",
      viewConfig: {
        enableTextSelection: true,
        markDirty: false
      },
      border: 0,
      plugins: [me._cellEditing],
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 40
      }), {
        header: "科目码",
        dataIndex: "subjectCode",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        width: 100,
        editor: {
          xtype: "psi_subjectfield",
          editOrgId: me.buildId(me, "editOrg"),
          callbackFunc: me._subjectEditorCallbackFunc,
          callbackScope: me,
        }
      }, {
        header: "科目名称",
        dataIndex: "subjectName",
        menuDisabled: true,
        sortable: false,
        width: 400,
        draggable: false,
      }, {
        header: "借方金额",
        dataIndex: "debit",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        align: "right",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          decimalPrecision: 2,
          hideTrigger: true,
          keyNavEnabled: false,
          mouseWheelEnabled: false,
        },
        renderer(value) {
          if (!value) {
            return null;
          }
          const s = PCL.util.Format.number(value, "0,0.00");
          if (value < 0) {
            return `<span style='color:red'>${s}</span>`;
          } else {
            return s;
          }
        }
      }, {
        header: "贷方金额",
        dataIndex: "credit",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        align: "right",
        width: 120,
        editor: {
          xtype: "numberfield",
          allowDecimals: true,
          decimalPrecision: 2,
          hideTrigger: true,
          keyNavEnabled: false,
          mouseWheelEnabled: false,
        },
        renderer(value) {
          if (!value) {
            return null;
          }
          const s = PCL.util.Format.number(value, "0,0.00");
          if (value < 0) {
            return `<span style='color:red'>${s}</span>`;
          } else {
            return s;
          }
        }
      }, {
        header: "摘要",
        dataIndex: "summary",
        menuDisabled: true,
        sortable: false,
        draggable: false,
        width: 400,
        editor: {
          xtype: "textfield"
        },
        tooltip: me.buildTooltip("录入时，回车键跳转"),
      }],
      store,
      listeners: {
        select: {
          fn: me._onVoucherDetailGridSelect,
          scope: me
        },
        cellclick() {
          return !me._readonly;
        },
      },
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  _onCellEditingAfterEdit(editor, e) {
    const me = this;
    if (e.colIdx == 5) {
      // 在最后一列编辑完后（通常是回车后），
      // 输入焦点的跳转逻辑是：先跳转到分录附加项
      // 如果没有分录附加项，再继续处理是否新增分录


      if (me.setFocusToFmtInputs()) {
        // 已经成功跳转到分录附加项Input
        return;
      }

      // 处理是否需要新增分录
      const store = me.getVoucherDetailGrid().getStore();
      if (e.rowIdx == store.getCount() - 1) {
        store.add({});
        const row = e.rowIdx + 1;
        me.getVoucherDetailGrid().getSelectionModel().select(row);
        me._cellEditing.startEdit(row, 1);
      }
    }
  },

  /**
   * @private
   */
  _onVoucherDetailGridSelect() {
    const me = this;

    me.createInputsFromFmtCols();
  },

  /**
   * @private
   */
  setVoucherReadonly() {
    const me = this;
    me._readonly = true;
    me.dfTitle.setValue(me.formatTitleLabel("记账凭证", "查看"));

    me.buttonSave.setVisible(false);
    me.buttonCancel.setText("关闭");

    me.editVoucherDT.setReadOnly(true);
    me.editChargeUser.setReadOnly(true);
    me.editCashUser.setReadOnly(true);
    me.editBizUser.setReadOnly(true);
    me.editBillNumber.setReadOnly(true);
  },

  /**
   * @private
   */
  _subjectEditorCallbackFunc(data) {
    const me = this;
    const item = me.getVoucherDetailGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const rec = item[0];

    rec.set("subjectCode", data.get("code"));
    rec.set("subjectName", data.get("name"));

    // 查询分录附加项
    me.queryFmtEx(data.get("code"));
  },

  /**
   * 查询分录附加项
   * 
   * @private
   */
  queryFmtEx(subjectCode) {
    const me = this;

    const companyId = me.editOrg.getValue();

    me.ajax({
      url: me.URL("SLN0002/Voucher/queryFmtEx"),
      params: {
        companyId,
        subjectCode,
      },
      callback(opt, success, response) {
        if (success) {
          const data = me.decodeJSON(response.responseText);
          const item = me.getVoucherDetailGrid().getSelectionModel().getSelection();
          if (item == null || item.length != 1) {
            return;
          }

          const rec = item[0];
          rec.set("fmtCols", data);

          me.createInputsFromFmtCols();
        }
      },
    });
  },

  /**
   * 根据账样扩展项创建凭证录入附加项
   * 
   * @private
   */
  createInputsFromFmtCols() {
    const me = this;

    me.panelFmtCols.removeAll();

    const item = me.getVoucherDetailGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }
    const rec = item[0];
    const fmtCols = rec.get("fmtCols");

    if (!fmtCols || fmtCols.length == 0) {
      return;
    }

    fmtCols.forEach((col, index) => {
      const input = {
        readOnly: me._readonly,
        cls: me._readonly ? "" : "PSI-voucher",
        _index: index,
        _colId: col.id, // 对应t_acc_fmt_cols表的id字段
        value: col.value,
        colspan: col.colspan,
        width: col.width,
        xtype: col.voucherInputXtype,
        beforeLabelTextTpl: PSI.Const.REQUIRED,
        fieldLabel: col.caption,
        labelAlign: "right",
        labelSeparator: "",
        labelWidth: 70,
        listeners: {
          specialkey: {
            fn: me._onFmtEditSpecialkey,
            scope: me
          },
          blur: {
            fn: me._onFmtEditBlur,
            scope: me,
          }
        },
      };

      // 日期
      if (col.voucherInputXtype == "datefield") {
        PCL.apply(input, {
          format: "Y-m-d",
          value: new Date(),
        });
      }

      // 数值
      if (col.voucherInputXtype == "numberfield") {
        PCL.apply(input, {
          hideTrigger: true,
          minValue: 0,
          allowDecimals: col.fieldDec > 0,
          decimalPrecision: col.fieldDec,
          hideTrigger: true,
          keyNavEnabled: false,
          mouseWheelEnabled: false,
        });
      }

      // 码表录入
      if (col.voucherInputXtype == "psi_codetable_voucherfield") {
        PCL.apply(input, {
          fid: col.fid,
          isCodeTable: true,
          initIdValue: col.codeId,
          companyIdFuncCallback() {
            return me.editOrg.getValue();
          },
          companyIdFuncCallbackScope: me,
        });
      }

      me.panelFmtCols.add(input);
    });
  },

  /**
   * 分录附加项处理回车事件
   * 
   * @private
   */
  _onFmtEditSpecialkey(field, e) {
    const me = this;

    if (e.getKey() === e.ENTER) {
      // 同步数据
      const value = field.getValue();
      if (!value) {
        me.showInfo(`没有输入分录附加项 <span style='color:red'>${field.fieldLabel}</span> 的数据`, () => {
          field.focus();
        });
        return;
      }

      const item = me.getVoucherDetailGrid().getSelectionModel().getSelection();
      if (item == null || item.length != 1) {
        return;
      }
      const rec = item[0];
      const fmtCols = rec.get("fmtCols");
      fmtCols.forEach((it) => {
        if (it.id == field._colId) {
          it.value = value;
          if (field.isCodeTable) {
            it.codeId = field.getIdValue();
            it.codeValue = field.getCodeValue();
            it.nameValue = field.getNameValue();
          }

          if (it.fmtCPM == "1") {
            // 数量字段
            me._cpmCalcPrice(rec, field);
          } else if (it.fmtCPM == "2") {
            // 单价字段
            me._cpmCalcPrice(rec, field);
          }
        }
      });


      // 处理跳转
      const input = me.panelFmtCols.getComponent(field._index + 1);
      if (input) {
        me.setFocusAndCursorPosToLast(input);
      } else {
        // 最后一个input了，需要重新跳转到Grid
        const store = me.getVoucherDetailGrid().getStore();
        store.add({});
        const row = store.getCount() - 1;
        me.getVoucherDetailGrid().getSelectionModel().select(row);
        me._cellEditing.startEdit(row, 1);
      }
    }
  },

  /**
   * 分录附加项字段失去录入焦点的事件处理函数
   * 
   * 用来同步数据
   */
  _onFmtEditBlur(field) {
    const me = this;

    const item = me.getVoucherDetailGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const rec = item[0];
    const fmtCols = rec.get("fmtCols");
    fmtCols.forEach((it) => {
      if (it.id == field._colId) {
        it.value = field.getValue();

        if (field.isCodeTable) {
          it.codeId = field.getIdValue();
          it.codeValue = field.getCodeValue();
          it.nameValue = field.getNameValue();
        }
      }
    });
  },

  /**
   * 把录入焦点设置到第一个分录附加项input上
   * 
   * @private
   */
  setFocusToFmtInputs() {
    const me = this;

    const input = me.panelFmtCols.getComponent(0);

    input?.focus();

    return input != null;
  },

  /**
   * @private
   */
  getSaveData(ignoreBalance = false) {
    const me = this;

    const result = {
      id: me.adding ? null : me.getEntity().get("id"),
      orgId: me.editOrg.getValue(),
      wordId: me.editWord.getValue(),
      voucherDT: me.toDT(me.editVoucherDT.getValue()),
      chargeUserId: me.editChargeUser.getIdValue(),
      cashUserId: me.editCashUser.getIdValue(),
      bizUserId: me.editBizUser.getIdValue(),
      billNumber: me.editBillNumber.getValue(),
      ignoreBalance: ignoreBalance ? "1" : "0",
      items: [], // 分录
    };

    const store = me.getVoucherDetailGrid().getStore();
    for (let i = 0; i < store.getCount(); i++) {
      const item = store.getAt(i);

      const fmtCols = item.get("fmtCols");
      const itemEx = [];
      if (fmtCols) {
        fmtCols.forEach((it) => {
          itemEx.push({
            colId: it.id,
            value: it.value,
            codeId: it.codeId,
            codeValue: it.codeValue,
            nameValue: it.nameValue,
          });
        });
      }

      result.items.push({
        id: item.get("id"),
        subjectCode: item.get("subjectCode"),
        debit: item.get("debit"),
        credit: item.get("credit"),
        summary: item.get("summary"),
        itemEx,
      });
    }

    return me.encodeJSON(result);
  },

  /**
   * 计算单价
   * @private
   */
  _cpmCalcPrice(rec, field) {
    const me = this;

    const debit = rec.get("debit");
    const credit = rec.get("credit");
    const isDebit = debit != null;

    const fmtCols = rec.get("fmtCols");
    fmtCols.forEach((it, idx) => {
      if (it.fmtCPM == "2") {
        // 当前字段是单价字段
        const input = me.panelFmtCols.getComponent(idx);

        const m = isDebit ? debit : credit;
        const price = m / field.getValue();

        input.setValue(price);
      }
    });
  },

  /**
   * 计算数量
   * @private
   */
  _cpmCalcCnt(rec, field) {
    // TODO
    // 目前不是现实由单价反过来计算数量
  },
});
